package com.example.chengzhong.config;

import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class SerialPortListener implements SerialPortEventListener {

    private  final String PORT_NAME = "COM1";
    private  final int BAUD_RATE = 1200;
    private  final int DATA_BITS = SerialPort.DATABITS_8;
    private  final int STOP_BITS = SerialPort.STOPBITS_1;
    private  final int PARITY = SerialPort.PARITY_NONE;

    private  SerialPort serialPort;
    private  InputStream inputStream;

    private  StringBuilder sb = new StringBuilder();
    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                byte[] buffer = new byte[1024*1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    String data = new String(buffer, 0, len);
                    sb.append(data);
                    if (data.endsWith("\n")) {
                        System.out.println("接收数据: " + sb);
                        sb = new StringBuilder();
                    }
//                        System.out.println("接收数据: " + data);
//                        if (data.contains("\n")){
//                            System.out.println("hahaha");
//                        }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
